package babo.cd.physicalexperiment.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.TwoLevelHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import babo.cd.physicalexperiment.BaseActivity;
import babo.cd.physicalexperiment.R;
import babo.cd.physicalexperiment.bean.MyDevicesListBean;
import babo.cd.physicalexperiment.bean.StartShiyanBean;
import babo.cd.physicalexperiment.bean.YuyueListbean;
import babo.cd.physicalexperiment.databinding.ActivityShebeilistBinding;
import babo.cd.physicalexperiment.dialog.DialogCommon;
import babo.cd.physicalexperiment.utils.OKCallback;
import babo.cd.physicalexperiment.utils.OkUtils;
import babo.cd.physicalexperiment.utils.Out;
import babo.cd.physicalexperiment.utils.URLS;
import babo.cd.physicalexperiment.view.RoundAngleImageView;

public class ShiyanListActivity extends BaseActivity {
    ActivityShebeilistBinding binding;
    int type=-1;
    BaseQuickAdapter adapter;
    DialogCommon dialogCommon;
    List<MyDevicesListBean.MyDeviceInfo> datas=new ArrayList<>();

    @Override
    protected View bindView() {
        binding=ActivityShebeilistBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        type=getIntent().getIntExtra("type",-1);
        binding.topbar.setCenterText("请选择实验设备");
        binding.smr.setRefreshHeader(new TwoLevelHeader(this));
        binding.smr.setRefreshFooter(new ClassicsFooter(this));
        binding.smr.setEnableLoadMore(false);
        binding.smr.setEnableRefresh(true);
        binding.rcv.setLayoutManager(new LinearLayoutManager(context));
        adapter=new BaseQuickAdapter( R.layout.item_mydevice,datas) {
            @Override
            protected void convert(BaseViewHolder helper, Object item) {
                bindConvert(helper,(MyDevicesListBean.MyDeviceInfo) item);
            }


        };
        binding.rcv.setAdapter(adapter);
    }

    @Override
    protected void loadData() {



    }

    @Override
    protected void onResume() {
        super.onResume();

        datas.clear();
        getDeviceList();
    }

    private void getDeviceList() {
        OkUtils.GetOk(URLS.getdevice+"?expId="+type,new OKCallback(context){
            @Override
            public void Sucess(String str) {

                super.Sucess(str);
                Out.out("实验设备body=="+str);
                try {
                    binding.smr.finishRefresh(300);
                }catch (Exception e){}
                MyDevicesListBean myDevicesListBean=gson.fromJson(str,MyDevicesListBean.class);
                datas.addAll(myDevicesListBean.getData());

                if (datas.size()>0){
                    binding.rcv.setVisibility(View.VISIBLE);
                    binding.txNodata.setVisibility(View.GONE);
                    adapter.notifyDataSetChanged();
                    int num=0;
                    for (int i=0;i<datas.size();i++){
                        if (datas.get(i).getStatus().equals("1")){
                            num=1;
                            break;
                        }
                    }
                    if (num>0){
                        binding.topbar.setRightText("");
                    }else{
                        binding.topbar.setRightText("预约实验");
                    }
                }else{
                    binding.rcv.setVisibility(View.GONE);
                    binding.txNodata.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void rightClick() {
        super.rightClick();
         Out.out("点击了预约实验");
         getMyyuyue();
    }
    private void getMyyuyue() {
        OkUtils.GetOk(URLS.getmyyuyue, new OKCallback(context) {
            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                Out.out("我的预约信息："+str);
                Gson gson = new Gson();
                try {
                    YuyueListbean    yuyueListbean = gson.fromJson(str, YuyueListbean.class);
                    if (yuyueListbean.getData().size()>0){
                        int find=-1;
                        for (int i=0;i<yuyueListbean.getData().size();i++){
                            if (Integer.parseInt(yuyueListbean.getData().get(i).getExpId())==type){
                                find=1;
                                break;
                            }
                        }
                        if (find>0){
                            Out.toast(context,"你已经预约过了，请耐心等待通知！");
                        }else{
                            doYuyue();
                        }

                    }else{
                        doYuyue();
                    }
                } catch (Exception ex) {
                    doYuyue();
                }

            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void setListener() {
        super.setListener();
        binding.smr.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                datas.clear();
                getDeviceList();
            }
        });

    }
    private void bindConvert(BaseViewHolder helper, MyDevicesListBean.MyDeviceInfo item) {
        TextView txname=helper.getView(R.id.txname);
        TextView txstatus=helper.getView(R.id.txstatus);
        TextView tx_caozuo=helper.getView(R.id.tx_caozuo);
        TextView txbianji=helper.getView(R.id.tx_bianij);
        txbianji.setVisibility(View.GONE);
        RoundAngleImageView ivhead=helper.getView(R.id.ivhead);
        if (!TextUtils.isEmpty(item.getImg())){
            Glide.with(context).load(item.getImg()).into(ivhead);
        }else{
            Glide.with(context).load(R.mipmap.zhanwei).into(ivhead);
        }
        txname.setText(item.getName());

        int stuas=Integer.parseInt(item.getStatus());
        if (stuas==1){
            txstatus.setText("空闲");
            txstatus.setTextColor(getResources().getColor(R.color.stausfree));
            tx_caozuo.setVisibility(View.VISIBLE);
            tx_caozuo.setText("开始实验");
            tx_caozuo.setTextColor(Color.parseColor("#FFFFFF"));
            tx_caozuo.setBackgroundResource(R.drawable.backbtnblue);
        }else if (stuas==2){
            txstatus.setText("实验中");
            txstatus.setTextColor(getResources().getColor(R.color.statususing));
            tx_caozuo.setVisibility(View.GONE);
        }else{
            txstatus.setText("维护中");
            txstatus.setTextColor(getResources().getColor(R.color.statusweihuzhong));
            tx_caozuo.setVisibility(View.VISIBLE);
            tx_caozuo.setVisibility(View.GONE);
        }

        tx_caozuo.setOnClickListener(v -> {
            dialogCommon=new DialogCommon(context);
            dialogCommon.setTitle("提示");
            dialogCommon.setCancel("取消", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialogCommon.dismiss();
                }
            });
            String msg="是否要在<font color='#FF0000'>"+item.getName()+"</font>上开始实验？";
            dialogCommon.setMessageHtml(msg);
            dialogCommon.show();
            dialogCommon.setConfirm("确定", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialogCommon.dismiss();
                   doStartShiyan(item);
                }
            });

        });

    }

    private void doStartShiyan(MyDevicesListBean.MyDeviceInfo item) {
       OkUtils.GetOk(URLS.startshiyan+"?deviceId="+item.getId(),new OKCallback(context){
           @Override
           public void Sucess(String str) {
               super.Sucess(str);
               Out.out("开始实验返回："+str);
               if (type==1){
                   StartShiyanBean startShiyanBean=gson.fromJson(str,StartShiyanBean.class);
                   Intent intent=new Intent(context,MaikeerxunActivity.class);
                   intent.putExtra("apid",startShiyanBean.getData().getAppointmentId());
                   intent.putExtra("purl",startShiyanBean.getData().getLivePullUrl());
                   intent.putExtra("pushurl",startShiyanBean.getData().getLivePushUrl());
                   intent.putExtra("did",item.getMac());
                   intent.putExtra("didfq",item.getId());
                   startActivityForResult(intent,80);
               }else{
                   StartShiyanBean startShiyanBean=gson.fromJson(str,StartShiyanBean.class);
                   Intent intent=new Intent(context,ZIyouluotiAcivity.class);
                   intent.putExtra("apid",startShiyanBean.getData().getAppointmentId());
                   intent.putExtra("purl",startShiyanBean.getData().getLivePullUrl());
                   intent.putExtra("pushurl",startShiyanBean.getData().getLivePushUrl());
                   intent.putExtra("did",item.getMac());
                   intent.putExtra("didfq",item.getId());
                   Out.out("purl=="+startShiyanBean.getData().getLivePullUrl());
                   Out.out("pushurl=="+startShiyanBean.getData().getLivePushUrl());
                   startActivityForResult(intent,80);

               }

           }
       });

    }

    private void doYuyue() {
        SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        String time11 = sdfTwo.format(System.currentTimeMillis());

        Out.out("当前时间：" + Uri.encode(time11));


        OkUtils.GetOk(URLS.doyuyue + "?expId=" + type + "&appointmentTime=" + Uri.encode(time11), new OKCallback(context) {
            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                Out.toast(context,"预约成功，请等待通知进行实验！");

            }

            @Override
            public void Eorror(int code) {
                super.Eorror(code);
                Out.out("do预约code=" + code);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==81){
            finish();
        }
    }
}
